import json
import re

from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.views import View
from fdfs_client.client import Fdfs_client

from houses.models import House
from utils.response_code import *


class UserCenterView(LoginRequiredMixin, View):
    def get(self, request):
        """获取个人信息"""

        user = request.user
        avatar = user.avatar
        if avatar:
            avatar_url = avatar.url
        else:
            avatar_url = ''

        user_data = {
            "avatar_url": avatar_url,
            "create_time": user.create_time,
            "mobile": user.mobile,
            "name": user.username,
            "user_id": user.id
        }

        return JsonResponse({
            'errno': 0,
            'errmsg': 'OK',
            'data': user_data
        })


class UploadAvatarView(LoginRequiredMixin, View):
    def post(self, request):
        """上传头像"""

        # 获取数据
        avatar = request.FILES.get('avatar')

        # 校验数据
        if not avatar:
            return JsonResponse({
                'errno': RET.PARAMERR,
                'errmsg': error_map[RET.PARAMERR]
            })

        # 连接fdfs上传头像
        avatar_buffer = avatar.read()
        fdfs_client = Fdfs_client(settings.BASE_DIR + '/utils/fdfs/client.conf')
        result = fdfs_client.upload_by_buffer(avatar_buffer)

        # 判断上传状态
        if result['Status'] != 'Upload successed.':
            return JsonResponse({
                'errno': RET.THIRDERR,
                'errmsg': error_map[RET.THIRDERR]
            })

        # 获取头像远程地址
        avatar_url = result['Remote file_id']
        user = request.user
        user.avatar = avatar_url
        user.save()

        # 返回响应
        return JsonResponse({
            'data': {
                'avatar_url': user.avatar.url
            },
            'errno': 0,
            'errmsg': '头像上传成功'
        })


class ModifyNameView(LoginRequiredMixin, View):
    def put(self, request):
        """修改用户名"""

        # 获取数据
        name = json.loads(request.body).get('name')

        user = request.user
        user.username = name
        user.save()

        return JsonResponse({
            'errno': '0',
            'errmsg': '修改成功'
        })


class UserRealNameAuthenticationView(LoginRequiredMixin, View):
    def post(self, request):
        """用户实名认证"""

        # 接收数据
        real_name = json.loads(request.body).get('real_name')
        id_card = json.loads(request.body).get('id_card')

        # 校验数据
        if not all([real_name, id_card]):
            return JsonResponse({
                'errno': RET.PARAMERR,
                'errmsg': error_map[RET.PARAMERR]
            })

        if not re.match('^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$', id_card):
            return JsonResponse({
                'errno': RET.PARAMERR,
                'errmsg': error_map[RET.PARAMERR]
            })

        if not re.match('^[\u4E00-\u9FA5]{2,4}$', real_name):
            return JsonResponse({
                'errno': RET.PARAMERR,
                'errmsg': error_map[RET.PARAMERR]
            })

        # 写入数据库
        user = request.user
        user.real_name = real_name
        user.id_card = id_card
        user.save()

        # 返回响应
        return JsonResponse({
            'errno': 0,
            'errmsg': '认证信息保存成功'
        })

    def get(self, request):
        """判断用户是否实名认证"""

        user = request.user
        if user.real_name and user.id_card:
            return JsonResponse({
                'errno': 0,
                'errmsg': '已实名认证',
                'data': {
                    'real_name': user.real_name,
                    'id_card': user.id_card
                }
            })

        else:
            return JsonResponse({
                'errno': 9999,
                'errmsg': '用户未实名认证'
            })

